#include <FreeRTOS.h>
#include <task.h>
#include <platform_stdlib.h>
#include <httpd/httpd.h>
#include "media_filesystem.h"
#include <string.h>
#include "emmc_file_server.h"

// 根据文件扩展名获取Content-Type
const char* get_content_type(const char* filename) {
    if (strstr(filename, ".mp4")) return "video/mp4";
    if (strstr(filename, ".jpg") || strstr(filename, ".jpeg")) return "image/jpeg";
    if (strstr(filename, ".png")) return "image/png";
    if (strstr(filename, ".csv")) return "text/csv";
    return "application/octet-stream";
}

void httpd_response_forbidden(struct httpd_conn *conn, char *msg) {
    httpd_response_write_header_start(conn, (char *)"403 Forbidden", (char *)"text/plain", strlen(msg));
    httpd_response_write_header(conn, (char *)"Connection", (char *)"close");
    httpd_response_write_header_finish(conn);
    httpd_response_write_data(conn, (unsigned char *)msg, strlen(msg));
}

// 假设eMMC挂载点为"/emmc"，实际使用时可能需要调整
#define EMMC_MOUNT_POINT "aiglass:/"
#define BUFFER_SIZE 4096

// 列出eMMC目录中的文件
void emmc_list_files_cb(struct httpd_conn *conn)
{
    const char *dir_path = EMMC_MOUNT_POINT;
    struct dirent **namelist;
    int n;

    // 确保eMMC已挂载
    //if (vfs_user_mount(EMMC_MOUNT_POINT) != 0) {
    //    httpd_response_internal_server_error(conn, (char *)"Failed to mount eMMC");
    //    httpd_conn_close(conn);
    //    return;
    //}
    // 只处理GET请求
    if (!httpd_request_is_method(conn, (char *)"GET")) {
        httpd_response_method_not_allowed(conn, NULL);
        httpd_conn_close(conn);
        return;
    }

    // 打开目录
    n = scandir(dir_path, &namelist, NULL, alphasort);
    if (n < 0) {
        httpd_response_internal_server_error(conn, (char *)"Failed to open directory");
    } else {
        // 构建HTML响应
        char response_body[4096] = {0};
        int response_len = 0;

        response_len += sprintf(response_body + response_len, "<HTML><BODY>");
        response_len += sprintf(response_body + response_len, "<H1>eMMC Files</H1>");
        response_len += sprintf(response_body + response_len, "<UL>");

        // 列出文件
        for (int i = 0; i < n; i++) {
            // 跳过.和..目录
            if (strcmp(namelist[i]->d_name, ".") == 0 || strcmp(namelist[i]->d_name, "..") == 0) {
                free(namelist[i]);
                continue;
            }

            // 构建文件链接
            if (namelist[i]->d_type == DT_DIR) {
                response_len += sprintf(response_body + response_len, "<LI><B>%s/</B></LI>", namelist[i]->d_name);
            } else {
                response_len += sprintf(response_body + response_len, "<LI><A href=\"/emmc_download?file=%s\">%s</A></LI>",
                                        namelist[i]->d_name, namelist[i]->d_name);
            }
            free(namelist[i]);
        }
        free(namelist);

        response_len += sprintf(response_body + response_len, "</UL></BODY></HTML>");

        // 发送HTTP响应头和内容
        httpd_response_write_header_start(conn, (char *)"200 OK", (char *)"text/html", response_len);
        httpd_response_write_header(conn, (char *)"Connection", (char *)"close");
        httpd_response_write_header_finish(conn);
        httpd_response_write_data(conn, (unsigned char *)response_body, response_len);
    }

    httpd_conn_close(conn);
}

// 下载eMMC中的文件
void emmc_download_file_cb(struct httpd_conn *conn)
{
    char *file_name = NULL;
    char file_path[PATH_MAX] = {0};
    vfs_file file;
    unsigned char buffer[BUFFER_SIZE];
    int read_size;
    struct stat file_stat;

    // 获取请求的文件名
    if (httpd_request_get_query_key(conn, (char *)"file", &file_name) == -1) {
        httpd_response_bad_request(conn, (char *)"Missing file parameter");
        httpd_conn_close(conn);
        return;
    }

    // 确保文件名安全，防止路径遍历攻击
    if (strstr(file_name, "..") != NULL) {
        httpd_response_forbidden(conn, (char *)"Invalid file name");
        httpd_free(file_name);
        httpd_conn_close(conn);
        return;
    }

    // 构建完整文件路径
    snprintf(file_path, sizeof(file_path), "%s/%s", EMMC_MOUNT_POINT, file_name);

    // 确保eMMC已挂载
    //if (vfs_user_mount(EMMC_MOUNT_POINT) != 0) {
    //    httpd_response_internal_server_error(conn, (char *)"Failed to mount eMMC");
    //    httpd_free(file_name);
    //    httpd_conn_close(conn);
    //    return;
    //}

    // 检查文件是否存在
    if (access(file_path, F_OK) != 0) {
        httpd_response_not_found(conn, (char *)"File not found");
        httpd_free(file_name);
        httpd_conn_close(conn);
        return;
    }

    // 获取文件信息
    if (stat(file_path, &file_stat) != 0) {
        httpd_response_internal_server_error(conn, (char *)"Failed to get file info");
        httpd_free(file_name);
        httpd_conn_close(conn);
        return;
    }

    // 打开文件
    if (fatfs_drv.open(file_path, "rb", &file) != 0) {
        httpd_response_internal_server_error(conn, (char *)"Failed to open file");
        httpd_free(file_name);
        httpd_conn_close(conn);
        return;
    }

    // 确定文件的Content-Type
    const char* content_type = get_content_type(file_name);

    // 发送HTTP响应头
       // 发送HTTP响应头
    httpd_response_write_header_start(conn, (char *)"200 OK", (char *)content_type, file_stat.st_size);

    char content_disp[128];
    snprintf(content_disp, sizeof(content_disp), "attachment; filename=\"%s\"", file_name);
    httpd_response_write_header(conn, (char *)"Content-Disposition", content_disp);

    httpd_response_write_header(conn, (char *)"Connection", (char *)"close");
    httpd_response_write_header_finish(conn);

    // 发送文件内容
    while ((read_size = fatfs_drv.read(buffer, 1, BUFFER_SIZE, &file)) > 0) {
        httpd_response_write_data(conn, buffer, read_size);
    }

    // 清理资源
    fatfs_drv.close(&file);
    httpd_free(file_name);
    httpd_conn_close(conn);
}

// 初始化eMMC文件服务器
void emmc_file_server_init(void)
{
    // 注册页面回调函数
    httpd_reg_page_callback((char *)"/emmc_list", emmc_list_files_cb);
    httpd_reg_page_callback((char *)"/emmc_download", emmc_download_file_cb);

    printf("eMMC File Server initialized. Access via /emmc_list\n");
}